import { Feature } from "ol";
import { createFeature } from "../create/createFeature";
import { createMultiPointGeometry, createPointGeometry } from "../create/createGeometry";
import { createVectorLayer } from "../create/createLayer";
import { createSource } from "../create/createSource";
import {
  PointStyleOptions,
  PointType,
  createPointStyle,
} from "../styles/pointsStyle";
import { transform4326to3857 } from "../utils/transform";
import { Coordinate } from "ol/coordinate";

export interface CreatePointOptions {
  geometryType?: "Point" | "MultiPoint";
  getLngKey?: string;
  getLatKey?: string;
  style?: PointStyleOptions<PointType>;
}

export function createPointLayer<T>(data: T[], options?: CreatePointOptions) {
  const features: Feature[] = [];
  const {
    getLngKey = "lng",
    getLatKey = "lat",
    geometryType = "Point",
  } = options || {};
  const points: Coordinate[] = [];
  data.forEach((item) => {
    const lng = item[getLngKey as keyof T];
    const lat = item[getLatKey as keyof T];
    if (lng !== undefined && lat !== undefined) {
      const coordinate = transform4326to3857([lng as number, lat as number]);

      if (geometryType === "Point") {
        const feature = createFeature(createPointGeometry(coordinate));
        const pointStyle = createPointStyle(options?.style);
        feature.setStyle(pointStyle);
        // feature.setStyle;
        feature.set("data", item);
        features.push(feature);
      } else if (geometryType === "MultiPoint") {
        points.push(coordinate);
      }
    }
  });

  if (geometryType === "MultiPoint") {
    const feature = createFeature(createMultiPointGeometry(points));
    const pointStyle = createPointStyle(options?.style);
    feature.setStyle(pointStyle);
    feature.set("data", 1);
    features.push(feature);
  }

  const source = createSource();
  source.addFeatures(features);

  const layer = createVectorLayer({
    source,
  });
  return layer;
}
